<?php

namespace Home\Controller;

use Think\Controller;
use Think\Cache\Driver\Redis;

class ApiController extends Controller {

    private $dataObj = '';

    public function index() {

        if ($this->auth()) {
            $this->responseMsg();
        } else {
            echo "The data come from unknow address!";
            exit;
        }
    }

    public function auth() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = C("TOKEN");
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            echo $_GET["echostr"];
            return true;
        } else {
            return false;
        }
    }

    public function responseMsg() {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)) {
            $this->dataObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $event = $this->dataObj->MsgType;

            switch ($event) {
                case "event":
                    $this->handle_event_info();
                    break;

                case "text":
                    $this->handle_text_info();
                    break;

                case "image":
                    $this->handle_image_info();
                    break;

                case "voice":
                    $this->handle_voice_info();

                case "video":
                    $this->handle_video_info();
                    break;
                case "location":
                    $this->handle_location_info();

                case "link":
                    $this->handle_link_info();
                    break;

                default:
                    break;
            }
        } else {
            echo "xxx";
            exit;
        }
    }

    private function handle_event_info() {
        $eventValue = $this->dataObj->Event;

        switch ($eventValue) {
            case "subscribe":
                $this->subscribe();
                break;
            case "unsubscribe":
                $this->unsubscribe();
                break;
            case "CLICK":
                $this->click();
                break;
            case "VIEW":
                $this->view();
                break;
        }
    }
    
    private function click(){
        $kw = $this->dataObj->EventKey;
        $this->handle_text_info($kw);
        }


    private function handle_text_info() {
        $keyWord = trim($this->dataObj->Content);
        $id = M("App")->where("username='" . $this->dataObj->ToUserName . "'")->getField("id");
        $reply_info = M("Keyword")->where("app_id=" . $id . " and word ='" . $keyWord . "'")->Field("sid,type")->find();
        $fromUsername = $this->dataObj->FromUserName;
        $toUsername = $this->dataObj->ToUserName;
        $time = time();
        if ($reply_info) {
            if ($reply_info['type'] == "news") {
                $data = M("Sucai")->where("id=" . $reply_info['sid'] . " and type='news' and state = 0 and app_id=" . $id)->Field("*")->find();
                $str = '<xml><ToUserName>' . $fromUsername . '</ToUserName><FromUserName>' . $toUsername . '</FromUserName><CreateTime>' . $time . '</CreateTime><MsgType>news</MsgType><ArticleCount>1</ArticleCount><Articles>';

                $str.='<item><Title>' . $data["title"] . '</Title><Description>' . $data["abstract"] . '</Description><PicUrl>http://' . $_SERVER[HTTP_HOST] . $data["cover"] . '</PicUrl><Url>' . $data["url"] . '</Url></item>';
                $str.='</Articles></xml>';
            } else if ($reply_info['type'] == "newses") {

                $data = M("Sucai")->where("pid=" . $reply_info["sid"] . " and state=0 and app_id =" . $id . " and type='news'")->order("id asc")->select();

                $num = count($data);
                $str = '<xml><ToUserName>' . $fromUsername . '</ToUserName><FromUserName>' . $toUsername . '</FromUserName><CreateTime>' . $time . '</CreateTime><MsgType>news</MsgType><ArticleCount>' . $num . '</ArticleCount><Articles>';

                foreach ($data as $v) {

                    $str.='<item><Title>' . $v["title"] . '</Title><Description>' . $v["abstract"] . '</Description><PicUrl>http://' . $_SERVER[HTTP_HOST] . $v["cover"] . '</PicUrl><Url>' . $v["url"] . '</Url></item>';
                }
                $str.='</Articles></xml>';
                
            } elseif ($reply_info['type'] == 'text') {
                $data = M("Sucai")->where("id=" . $reply_info['sid'] . " and type='text' and state = 0 and app_id=" . $id)->Field("content")->find();
                $contentStr = $data["content"];
                $msgType = "text";

                $textTpl = $this->select_reply_tpl($msgType);

                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);

                echo $resultStr;
                exit;
            }elseif($reply_info['type'] == 'image'){
                $mediaId = $reply_info["sid"];
                $msgType = "image";
                $imgTpl = $this->select_reply_tpl($msgType);
                $resultStr = sprintf($imgTpl,$fromUsername,$toUsername,$time,$msgType,$mediaId);
                echo $resultStr;
                exit;
            }


            echo $str;
        }
    }

    private function subscribe() {
        $fromUsername = $this->dataObj->FromUserName;
        $toUsername = $this->dataObj->ToUserName;
        $time = time();
        $contentStr = M("App")->where("username='" . $toUsername . "'")->getField("welcomes");
        $msgType = "text";

        $textTpl = $this->select_reply_tpl($msgType);

        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);

        echo $resultStr;
    }

    private function testx($content) {
        $fromUsername = $this->dataObj->FromUserName;
        $toUsername = $this->dataObj->ToUserName;
        $time = time();
        //$contentStr = M("App")->where("username='".$toUsername."'")->getField("welcomes");
        $msgType = "text";

        $textTpl = $this->select_reply_tpl($msgType);
        $contentStr = $content;
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);

        echo $resultStr;
    }

    private function select_reply_tpl($type) {

        switch ($type) {
            case "text":
                $Tpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                </xml>";
                break;

            case "image":
                $Tpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Image>
                                    <MediaId><![CDATA[%s]]></MediaId>
                                </Image>
                                </xml>";
                break;
        }

        return $Tpl;
    }

    //二维码统计
    private function qrcode_cont(&$data, $type, &$redis) {
        if (!$redis->get($data['ToUserName'] . $data['FromUserName'] . $data['EventKey'] . $type)) {
            $data['app_id'] = D('App')->where(array('username' => $data['ToUserName']))->getField('id');
            $data['openid'] = $data['FromUserName'];
            $data['scene_id'] = str_replace('qrscene_', '', $data['EventKey']);
            $data['addtime'] = $data['CreateTime'];
            $data['type'] = $type;
            D('Qr_code_count')->add($data);
            $redis->set($data['ToUserName'] . $data['FromUserName'] . $data['EventKey'] . $type, $data['CreateTime'], 3);
        }
    }

    //保存消息
    private function save($data) {
        $data['app_id'] = D('App')->where(array('username' => $data['ToUserName']))->getField('id');
        $data['openid'] = $data['FromUserName'];
        $mod = D('message');
        $data = $mod->create($data);
        $mod->add($data);
    }

}